// Copyright (C) 2025, ZWSOFT Co., LTD.(Guangzhou)
// Licensed under the MIT License. See LICENSE in the project root for license information.

using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using TestClient.Domain;

namespace TestClient.ViewModel;
public partial class LoopCurveOpsTestViewModel : PageViewModelBase
{
    [ObservableProperty]
    private string surfaceId = "";
    [ObservableProperty]
    private string boundaryId = "";
    [ObservableProperty]
    private string curveId = "";
    [ObservableProperty]
    private string resultStr = "";

    public IAsyncRelayCommand SelectSurfaceCommand { get; }
    public IAsyncRelayCommand SelectBoundaryCommand { get; }
    public IAsyncRelayCommand SelectCurveCommand { get; }
    public IAsyncRelayCommand CheckRelPosCommand { get; }
    public IAsyncRelayCommand TrimInsideLoopCommand { get; }

    public LoopCurveOpsTestViewModel(VFAdapterWrapper wrapper, ISnackNotifyService notifyService)
        : base(wrapper, notifyService)
    {
        SelectSurfaceCommand = CreateAsyncRpcCommand(SelectSurfaceAsync);
        SelectBoundaryCommand = CreateAsyncRpcCommand(SelectBoundaryAsync);
        SelectCurveCommand = CreateAsyncRpcCommand(SelectCurveAsync);
        CheckRelPosCommand = CreateAsyncRpcCommand(CheckRelPosAsync);
        TrimInsideLoopCommand = CreateAsyncRpcCommand(TrimInsideLoopAsync);
    }

    private async Task SelectSurfaceAsync()
    {
        EnsureConnected();
        SurfaceId = await ViewModelHelpers.SelectEnt(Wrapper, "Surface");
    }

    private async Task SelectBoundaryAsync()
    {
        EnsureConnected();
        BoundaryId = await ViewModelHelpers.SelectEnt(Wrapper, "Curve");
    }

    private async Task SelectCurveAsync()
    {
        EnsureConnected();
        CurveId = await ViewModelHelpers.SelectEnt(Wrapper, "Curve");
    }

    private async Task CheckRelPosAsync()
    {
        EnsureConnected();
        var result = await Task.Run(() =>
        {
            return Wrapper.TestCurveOnSurface(SurfaceId, BoundaryId, CurveId);
        });

        ResultStr = result switch
        {
            0 => "Outside",
            1 => "Intersect",
            2 => "Inside",
            _ => "Error"
        };
    }

    private async Task TrimInsideLoopAsync()
    {
        EnsureConnected();
        ResultStr = await Task.Run(() =>
        {
            return Wrapper.CreateSpliteCurve(SurfaceId, CurveId, BoundaryId);
        });
    }
}
